import * as https from 'https';
import * as http from 'http';

async function testDownload(url: string) {
  console.log(`测试下载: ${url}`);

  return new Promise((resolve, reject) => {
    const protocol = url.startsWith('https:') ? https : http;
    const urlObj = new URL(url);

    const options = {
      hostname: urlObj.hostname,
      port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
      path: urlObj.pathname + urlObj.search,
      method: 'GET',
      timeout: 30000,
      headers: {
        'Host': urlObj.hostname,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Connection': 'keep-alive',
        'Referer': 'https://editor.appthen.com/'
      }
    };

    console.log('请求选项:', JSON.stringify(options, null, 2));

    const request = protocol.request(options, (response) => {
      console.log(`响应状态: HTTP ${response.statusCode} ${response.statusMessage}`);
      console.log('响应头:', JSON.stringify(response.headers, null, 2));

      if (response.statusCode && (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 307 || response.statusCode === 308)) {
        const location = response.headers.location;
        if (location) {
          console.log(`重定向到: ${location}`);
          testDownload(location).then(resolve).catch(reject);
          return;
        }
      }

      if (!response.statusCode || response.statusCode < 200 || response.statusCode >= 300) {
        reject(new Error(`HTTP ${response.statusCode}: ${response.statusMessage || 'Unknown Status'}`));
        return;
      }

      const chunks: Buffer[] = [];
      let totalLength = 0;

      response.on('data', (chunk) => {
        chunks.push(chunk);
        totalLength += chunk.length;
        console.log(`接收到数据块: ${chunk.length} bytes, 总计: ${totalLength} bytes`);
      });

      response.on('end', () => {
        try {
          const buffer = Buffer.concat(chunks);
          console.log(`下载完成: ${buffer.length} bytes`);
          resolve(buffer);
        } catch (error) {
          console.error('合并缓冲区失败:', error);
          reject(error);
        }
      });

      response.on('error', (error) => {
        console.error('响应流错误:', error);
        reject(error);
      });
    });

    request.on('error', (error) => {
      console.error('请求错误:', error);
      reject(error);
    });

    request.on('timeout', () => {
      console.error('请求超时');
      request.destroy();
      reject(new Error('请求超时'));
    });

    request.on('socket', (socket) => {
      socket.on('error', (error) => {
        console.error('Socket错误:', error);
        reject(error);
      });
    });

    console.log('发起请求...');
    request.end();
  });
}

// 测试不同的URL
async function runTests() {
  const testUrls = [
    'https://cdn.appthen.com/Fp_s_XBf9C1PhnPplQWi0Udx8cw4',
    'https://cdn.appthen.com/Fmk8IZVxeE9QYk9hKJM-D2L4Q52_',
    'https://httpbin.org/image/png', // 测试用图片
    'https://res.wx.qq.com/open/js/jweixin-1.6.0.js' // 外部资源
  ];

  for (const url of testUrls) {
    try {
      console.log('\n' + '='.repeat(60));
      const buffer = await testDownload(url) as Buffer;
      console.log(`✅ 成功下载 ${buffer.length} bytes`);
    } catch (error) {
      console.error(`❌ 下载失败: ${error.message}`);
    }
  }
}

// 运行测试
if (require.main === module) {
  runTests().catch(console.error);
}

export { testDownload, runTests };